<?php
/**
 * @date 2012-2-28
 * @author GhostWei
 */
abstract class system_passport_storage_abstract implements system_passport_storage_interface {
	
	protected $_namespace = 'PASSPORT';
	protected $_data = null;
	protected $_sessionOptions = array();
	
	public function __construct($namespance) {
		$this->_namespace = $namespance;
		$this->_sessionOptions = system_session::getOptions();
	}
	
	public function hasData() {
		return !($this->readData()===null);
	}
	
	public function setId($id) {
		$this->_data['id'] = $id;
		return $this;
	}
	public function getId() {
		if($this->_data === null) {
			$this->readData();
		}
		return isset($this->_data['id']) ? $this->_data['id'] : null;
	}
	
	public function setIdentity($identity) {
		$this->_data['identity'] = $identity;
		return $this;
	}
	public function getIdentity() {
		if($this->_data === null) {
			$this->readData();
		}
		return isset($this->_data['identity']) ? $this->_data['identity'] : null;
	}
	
	public function setSecurity($is = false) {
		$this->_data['security'] = ($is ? md5(system_session::getId()) : null);
		return $this;
	}
	public function getSecurity() {
		if($this->_data === null) {
			$this->readData();
		}
		return isset($this->_data['security']) ? $this->_data['security'] : null;
	}	
	
	public function setLanguage($language = null) {
		$this->_data['language'] = $language;
		return $this;
	}
	public function getLanguage() {
		if($this->_data === null) {
			$this->readData();
		}
		return isset($this->_data['language']) ? $this->_data['language'] : $this->_defaultLanguage();
	}
	
	private function _defaultLanguage() {
		$lang = system_controller_front::getInstance()->getRequest()->getServer('HTTP_ACCEPT_LANGUAGE');
		if($lang && strlen($lang) >= 5) {
			$lang = substr($lang, 0, 5);
			$lang = str_replace('-', '_', $lang);
			return preg_replace_callback(
					'/^([a-zA-Z]{2})_([a-zA-Z]{2})$/is', 
					create_function('$m', 'return strtolower($m[1])."_".strtoupper($m[2]);'), 
					$lang
				);
		}
		return 'en_US';
	}
	
}